﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DisplayBoardInfo.Server.Model;

namespace DisplayBoardInfo.Server.Session.MessageHandlers
{
    class AddAppointmentsHandler : MessageHandler
    {
        IEnumerable<Network.Messages.Content.Appointment> appointments;
        DatabaseContextDataContext db = new DatabaseContextDataContext();

        public AddAppointmentsHandler(IEnumerable<Network.Messages.Content.Appointment> appointments)
        {
            this.appointments = appointments;
        }

        public override Network.Messages.NetworkMessage GetResult()
        {
            try
            {
                short k = 1;
                foreach (Network.Messages.Content.Appointment item in appointments)
                {
                    if (item.ID == -1)
                    {
                        Model.Patient p = new Patient();
                        p.LastName = item.Patient.LastName;
                        p.Name = item.Patient.Name;
                        p.PESEL = item.Patient.PESEL;
                        db.Patients.InsertOnSubmit(p);

                        Model.Appointment a = new Appointment();
                        a.DateTime = item.Date;
                        a.Doctor = item.Doctor.Username;
                        a.Patient = p;
                        a.Number = k;
                        a.Time = item.ExpectedTime;

                        db.Appointments.InsertOnSubmit(a);
                    }
                    else
                    {
                        Entities.Appointment a = new Entities.Appointment(item.ID);
                        a.Number = k;
                        a.Save();
                    }
                    k++;
                }
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Logger.Message(Logger.LogMessageType.Error, ex.Message);
                return new Network.Messages.NetworkMessage(Network.Messages.NetworkMessageTypes.Error, ex.Message);
            }

            Logger.Logger.Message(Logger.LogMessageType.Info, "Dodano pomyślnie nowe wizyty.");

            return new Network.Messages.NetworkMessage(Network.Messages.NetworkMessageTypes.OK, "Dodano pomyślnie.");
        }
    }
}
